package com.ldy.gkrpc.client;

import com.ldy.gkrpc.common.utils.ReflectionUtils;
import com.ldy.gkrpc.proto.Peer;
import com.ldy.gkrpc.transport.TransportClient;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Description
 * @Author
 * @Date 2020/4/14 20:42
 **/
@Slf4j
public class RandomTransportSelector implements TransportSelector{
    /**
     * 连接好的client
     */
    private List<TransportClient> clients =new ArrayList<>();
    @Override
    public void init(List<Peer> peers, int count, Class<? extends TransportClient> clazz) {
        int max = Math.max(count, 1);
        for (Peer peer : peers) {
            for (int i = 0; i < max; i++) {
                TransportClient client = ReflectionUtils.newInstance(clazz);
                client.connect(peer);
                clients.add(client);
            }
            log.info("connect server :{}",peer);
        }
    }

    @Override
    public TransportClient select() {
        int i = new Random().nextInt(clients.size());
        return clients.remove(i);
    }

    @Override
    public void release(TransportClient client) {
        clients.add(client);
    }

    @Override
    public void close() {
        for (TransportClient client : clients) {
            client.close();
        }
        clients.clear();
    }
}
